import React, { useState, useEffect } from 'react';
import apiClient from '../../utils/apiClient';
import './index.css';

const EditDocumentPage = ({ kbId, kbName, docId }) => {
  const [document, setDocument] = useState(null);
  const [isLoading, setIsLoading] = useState(true);
  const [title, setTitle] = useState('');
  const [file, setFile] = useState(null);
  const [uploadProgress, setUploadProgress] = useState(0);
  const [isUploading, setIsUploading] = useState(false);
  const [enableQAExtraction, setEnableQAExtraction] = useState(true);
  const [enableIndexEnhancement, setEnableIndexEnhancement] = useState(true);
  const [saveSuccess, setSaveSuccess] = useState(false);

  useEffect(() => {
    setIsLoading(true);
    
    apiClient.get(`/documents/${docId}`).then(response => {
      const docData = response.data;
      setDocument(docData);
      setTitle(docData.title);
      setIsLoading(false);
    }).catch(error => {
      console.error('Failed to fetch document details:', error);
      alert('加载文档信息失败');
      setIsLoading(false);
    });
  }, [docId, kbId, kbName]);

  const handleFileChange = (event) => {
    if (event.target.files && event.target.files[0]) {
      setFile(event.target.files[0]);
    }
  };

  const simulateUpload = () => {
    return new Promise((resolve, reject) => {
      setIsUploading(true);
      setUploadProgress(0);
      
      const interval = setInterval(() => {
        setUploadProgress(prev => {
          const newProgress = prev + 10;
          if (newProgress >= 100) {
            clearInterval(interval);
            setIsUploading(false);
            resolve();
          }
          return newProgress;
        });
      }, 300);
    });
  };

  const handleSubmit = async (e) => {
    e.preventDefault();
    setSaveSuccess(false);
    
    try {
      let uploadResponse = null;
      if (file) {
      // 使用正确的API路径进行文件上传
      uploadResponse = await apiClient.uploadFile(`/documents/${docId}/upload`, formData, (progress) => {
        setUploadProgress(progress);
      });
      }
      
      // 使用正确的API路径更新文档信息
      await apiClient.put(`/documents/${docId}`, {
        title,
        qa_extraction: enableQAExtraction,
        index_enhancement: enableIndexEnhancement,
        ...(uploadResponse ? { file_id: uploadResponse.fileId } : {})
      });
      
      // 显示成功消息
      setSaveSuccess(true);
      
      // 3秒后自动返回文档列表
      setTimeout(() => {
        window.location.hash = `#/kb/${kbId}?name=${encodeURIComponent(kbName)}`;
      }, 3000);
    } catch (error) {
      console.error('保存失败:', error);
      alert('保存失败，请重试');
    }
  };

  if (isLoading) {
    return <div className="container"><p className="loading-text">正在加载文档信息...</p></div>;
  }

  return (
    <div className="container edit-document-page">
      <div className="page-header">
        <h1>编辑文档</h1>
        <button 
          onClick={() => window.location.hash = `#/kb/${kbId}`} 
          className="secondary"
        >
          <i className="fas fa-arrow-left"></i> 返回知识库
        </button>
      </div>

      {saveSuccess && (
        <div className="success-message">
          <i className="fas fa-check-circle"></i> 文档已成功更新！即将返回知识库...
        </div>
      )}

      <form onSubmit={handleSubmit} className="edit-form">
        <div className="form-group">
          <label htmlFor="doc-title">文档标题</label>
          <input
            type="text"
            id="doc-title"
            value={title}
            onChange={(e) => setTitle(e.target.value)}
            required
            className="form-control"
          />
        </div>

        {document && (
          <>
            <div className="form-group">
              <label>当前文档类型</label>
              <div className="static-field">{document.type}</div>
            </div>

            <div className="form-group">
              <label>当前状态</label>
              <div className="static-field">
                <span className={`status-badge status-${document.status}`}>
                  {document.status}
                </span>
              </div>
            </div>

            <div className="form-group">
              <label>最后更新时间</label>
              <div className="static-field">{document.lastUpdated}</div>
            </div>
          </>
        )}

        <div className="form-divider"></div>

        <div className="form-group">
          <label htmlFor="doc-file">重新上传文档 (可选)</label>
          <div className="file-upload-container">
            <input
              type="file"
              id="doc-file"
              onChange={handleFileChange}
              className="file-input"
            />
            <label htmlFor="doc-file" className="file-upload-label">
              <i className="fas fa-cloud-upload-alt"></i> 
              {file ? file.name : '选择文件'}
            </label>
            {file && <span className="file-name">{file.name}</span>}
          </div>
        </div>

        {file && (
          <div className="upload-options">
            <div className="option-item">
              <input
                type="checkbox"
                id="qa-extraction"
                checked={enableQAExtraction}
                onChange={(e) => setEnableQAExtraction(e.target.checked)}
              />
              <label htmlFor="qa-extraction">
                <i className="fas fa-question-circle"></i> 开启QA提取
              </label>
            </div>
            <div className="option-item">
              <input
                type="checkbox"
                id="index-enhancement"
                checked={enableIndexEnhancement}
                onChange={(e) => setEnableIndexEnhancement(e.target.checked)}
              />
              <label htmlFor="index-enhancement">
                <i className="fas fa-search-plus"></i> 开启索引增强
              </label>
            </div>
          </div>
        )}

        {isUploading && (
          <div className="upload-progress">
            <div className="progress-bar-container">
              <div 
                className="progress-bar" 
                style={{ width: `${uploadProgress}%` }}
              ></div>
            </div>
            <div className="progress-text">{uploadProgress}%</div>
          </div>
        )}

        <div className="form-actions">
          <button 
            type="submit" 
            className="primary-btn"
            disabled={isUploading}
          >
            <i className="fas fa-save"></i> 保存更改
          </button>
        <button 
          type="button" 
          className="secondary-btn"
          onClick={() => window.location.hash = `#/kb/${kbId}`}
          disabled={isUploading}
        >
          取消
          >
            取消
          </button>
        </div>
      </form>
    </div>
  );
};

export default EditDocumentPage;
